<template>
  <BasicModal 
    v-bind="$attrs" 
    @register="registerModal" 
    :title="title" 
    @ok="handleSubmit" 
    width="600px" 
    destroyOnClose
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
import {computed, reactive, ref, unref} from 'vue';
import {BasicModal, useModalInner} from '/@/components/Modal';
import {BasicForm, useForm} from '/@/components/Form/index';
import {formSchema} from './dataGroup.data';
import {listDataGroupTree} from '/@/api/infra/dataGroup';
import {useMessage} from '/@/hooks/web/useMessage'
import {isFunction} from '/@/utils/is';

interface State {
  saveOrUpdateApi: Function;
  groupType?: string;
  isTree?: boolean;
  bizType?: string | number;
}
const { createMessage } = useMessage()
// 声明Emits
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const state = reactive<State>({
  saveOrUpdateApi: () => {}
})

//表单配置
const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
  schemas: formSchema,
  showActionButtonGroup: false
});
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  state.groupType = data.groupTpe
  state.saveOrUpdateApi = data.saveOrUpdateApi
  state.isTree = data.isTree
  state.bizType = data.bizType
  if (!isFunction(state.saveOrUpdateApi)) {
    console.log('data', data);
    createMessage.error('saveOrUpdateApi不是一个函数')
    closeModal()
    return
  }

  if (!state.bizType) {
    createMessage.error('bizType不能为空')
    closeModal()
    return
  }

  await resetFields();
  setModalProps({ confirmLoading: false, draggable: false, canFullscreen: false});
  isUpdate.value = !!data?.isUpdate;
  //表单赋值
  await setFieldsValue({ isTree: state.isTree, ...data.record });
  if (state.isTree) {
    const treeData = await listDataGroupTree({ bizType:  state.bizType, groupType: state.groupType});
    updateSchema([
      {
        field: 'parentId',
        componentProps: { treeData },
      }, 
    ])
  }
  
});


//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
//表单提交事件
async function handleSubmit(v) {
  try {
    let values = await validate();
    setModalProps({ confirmLoading: true });
    await state.saveOrUpdateApi({...values, groupType: state.groupType}, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
    createMessage.success(`${title.value}分组成功`)
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>
